package cn.wolfcode.wolf2w.controller;


import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.domain.Visitors;
import cn.wolfcode.wolf2w.interceptor.UserParam;
import cn.wolfcode.wolf2w.redis.IVisitorRedisService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.service.IVisitorsService;
import cn.wolfcode.wolf2w.util.JsonResult;
import cn.wolfcode.wolf2w.util.VisitorVo;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.plugin.javascript.navig.Array;
import sun.reflect.generics.visitor.Visitor;

import java.util.*;

@RestController
@RequestMapping("visitor")
public class VisitorController {

       @Autowired
       private IVisitorsService visitorsService;

       @Autowired
       private IUserInfoService userInfoService;

       @Autowired
       private IVisitorRedisService visitorRedisService;


    @GetMapping("detail")
    public Object detail(String id, @UserParam UserInfo userInfo) {
        //判断当前登录用户id是否与ownerId一致
        if(!id.equals(userInfo.getId())){
            visitorRedisService.incrVisitor(id,userInfo.getId());
        }
        //查询vo对象
        VisitorVo vo = visitorRedisService.queryVisitor(id);
        //获取vo对象中访客id
        List<String> visitorId = vo.getVisitorIds();
        List<UserInfo> list = new ArrayList<>();
        //循环遍历访客id，获取访客信息
        for (String vid : visitorId) {
           list.add(userInfoService.get(vid));
        }
        Collections.reverse(list);
        if(list.size()>=8){
            list = list.subList(0, 8);
        }
        Map<Object, Object> map = new HashMap<>();
        map.put("visitors",list);
         map.put("totalView",vo.getTotalView());
        return JsonResult.success(map);
    }

    @GetMapping("todayView")
    public Object todayView(String id,@UserParam UserInfo userInfo){
           if(!id.equals(userInfo.getId())){
               visitorRedisService.incrTodayView(id,userInfo.getId());
           }
        Long todayView = visitorRedisService.queryTodayView(id);
        return JsonResult.success(todayView);
    }

    @GetMapping("fans")
    public Object fans(String id){
        Visitors visitor = visitorsService.findByOwnerId(id);
        List<String> visitorIds = visitor.getVisitorIds();
        List<UserInfo> list = new ArrayList<>();
        for (String visitorId : visitorIds) {
            list.add(userInfoService.get(visitorId));
        }
        return JsonResult.success(list);
    }



}
